package com.lg;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Java三个线程依次序打印1-100
 * 互斥锁+条件变量
 * 
 * @author kaifa002
 *
 */
public class Main {
	public static void main(String[] args) {
		Task task = new Task();
		
		Thread thread1 = new Thread(() -> task.print(0), "thread 1");
		Thread thread2 = new Thread(() -> task.print(1), "thread 2");
		Thread thread3 = new Thread(() -> task.print(2), "thread 3");

		thread1.start();
		thread2.start();
		thread3.start();
	}
}

class Task {
	private int count = 1;
	private Lock lock = new ReentrantLock();
	private Condition condition = lock.newCondition();

	public void print(int id) {
		while (true) {
			lock.lock();
			try {
				while (count % 3 != id) {
					condition.await();
				}
				if (count > 100) {
					break;
				}
				System.out.println(Thread.currentThread().getName() + ": " + count);
				count++;
				condition.signalAll();
			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			} finally {
				lock.unlock();
			}
		}
	}
}


